<template>
  <view class="submit-bar" :data-theme="globPrimary">
    <view class="placeholder"></view>
    <view class="navigation">
      <view class="left">
        <view class="item" @click="pathMessage(courseInfo.online_consult)">
          <u-icon name="server-man" :size="44" color="#606266"></u-icon>
          <view class="text u-line-1">咨询</view>
        </view>
        <view class="item u-rela" @click="onGoCart">
          <u-badge :count="getGlobCartNumber" :offset="[-3, -6]" show-zero></u-badge>
          <u-icon name="shopping-cart" :size="44" color="#606266"></u-icon>
          <view class="text u-line-1">购物车</view>
        </view>
      </view>
      <view class="right" v-if="!$u.test.empty(courseInfo)">
        <!-- 课程已购买 -->
        <view v-if="courseInfo.is_buy == 1" class="big btn u-line-1" @click="onStartLearning">{{
          courseInfo.is_learning == 0 ? '开始学习' : '继续学习'
        }}</view>
        <!-- 无活动或者免费或者活动未开始 -->
        <template
          v-else-if="
            $u.test.empty(courseInfo.promotion) ||
            courseInfo.user_price == 0 ||
            courseInfo.promotion.running_status == 0
          "
        >
          <view class="cart btn u-line-1" @click="addCart" v-if="courseInfo.user_price > 0"
            >加入购物车</view
          >
          <view
            class="buy btn u-line-1"
            @click="onJion(courseInfo.user_price, courseInfo.promotion.id)"
            >加入学习</view
          >
        </template>
        <template v-else>
          <view
            class="buy btn u-line-1"
            v-if="btnType"
            @click="onJion(courseInfo.user_price, courseInfo.promotion.id)"
            >立即加入</view
          >
          <!-- 砍价 -->
          <template v-else-if="courseInfo.promotion.type == 3">
            <view
              class="cart btn u-line-1"
              @click="onJion(courseInfo.user_price, courseInfo.promotion.id)"
              >立即加入</view
            >
            <view
              class="buy btn u-line-1"
              @click="
                onJump('/pageCourse/course/promotion/bargain', {
                  id: courseInfo.promotion.id,
                })
              "
              >邀请砍价</view
            >
          </template>

          <template v-else-if="courseInfo.promotion.type == 4">
            <!-- 未开团 -->
            <view
              class="cart btn u-line-1"
              v-if="courseInfo.have_pintuan == 0"
              @click="onJion(courseInfo.user_price, '0')"
              >立即加入</view
            >
            <view
              class="buy btn u-line-1"
              @click="handleAddPintuan"
              v-if="courseInfo.have_pintuan == 0"
              >发起拼团</view
            >
            <!-- 以开团 -->
            <template v-else>
              <template v-if="courseInfo.pintuan_data.status == 0">
                <view class="cart btn u-line-1" @click="onJion(courseInfo.user_price, '0')"
                  >立即加入</view
                >
                <view
                  class="buy btn u-line-1"
                  @click="handleAddPintuan_nopay(courseInfo.pintuan_data.status)"
                  >发起拼团</view
                >
              </template>
              <!-- 已开团，团购失败 -->
              <template v-if="courseInfo.pintuan_data.status == 3">
                <view
                  class="cart btn u-line-1"
                  @click="onJion(courseInfo.user_price, courseInfo.promotion.id)"
                  >立即加入</view
                >
                <view class="buy btn u-line-1" @click="handleAddPintuan">发起拼团</view>
              </template>
              <!-- 成功开团 -->
              <view
                v-if="courseInfo.pintuan_data.status == 1"
                class="buy btn u-line-1"
                @click="
                  onJump('/pageCourse/course/promotion/pintuan', {
                    id: courseInfo.pintuan_data.id,
                    pro_id: courseInfo.promotion.id,
                  })
                "
              >
                {{
                  `已参团${courseInfo.pintuan_data.join_num}/${courseInfo.pintuan_data.total_num}人`
                }}
              </view>
            </template>
          </template>
        </template>
      </view>
    </view>
    <!-- 拼团列表弹窗 -->
    <pintuan-popup
      :visible.sync="showPintuan"
      :promotion="courseInfo.promotion"
      v-if="!$u.test.empty(courseInfo.promotion)"
    ></pintuan-popup>
    <!-- 人脸 -->
    <edu-face ref="refFaceVerify" @confirm="onFaceVerifyConfirm"></edu-face>
  </view>
</template>

<script>
// 获取当前页面的参数
import getCurPage from '@/utils/getCurPage.js'
import PintuanPopup from './pintuan-popup.vue'
import { mapState, mapGetters } from 'vuex'
import { uploadFile } from '@/utils/uploadFile.js'
// #ifdef APP-PLUS
const ccLiveUniPlugin = uni.requireNativePlugin('Bokecc-CcLiveUniPlugin')
const ccSsktUniPlugin = uni.requireNativePlugin('Bokecc-CcClassUniPlugin')
// #endif
export default {
  components: {
    PintuanPopup,
  },
  props: {
    courseInfo: {
      type: Object,
      default() {
        return {}
      },
    },
  },
  data() {
    return {
      showPintuan: false,
      options: {},
      directoryItemData: null,
    }
  },
  computed: {
    ...mapState({
      globConfigInit: (state) => state.projectSetting.globConfigInit,
      getGlobCartNumber: (state) => state.projectSetting.globCartNumber,
    }),
    ...mapGetters({
      globPrimary: 'designSetting/getGlobTheme',
      globPrimaryColor: 'designSetting/getGlobThemeColor',
      userInfo: 'user/getUserInfo',
      token: 'user/getToken',
    }),
    btnType() {
      let type = this.courseInfo.promotion && this.courseInfo.promotion.type
      return type == 1 || type == 2 ? true : false
    },
  },
  mounted() {
    this.options = getCurPage()
  },
  methods: {
    onGoCart(u, params) {
      this.$edu.judgeLogin(() => {
        this.$u.route('/pageCourse/cart/cart')
      })
    },
    // 加入购物车
    addCart() {
      this.$edu.judgeLogin(() => {
        this.$edu.api
          .postCoursePaymentCart({
            course_id: this.options.id,
          })
          .then((res) => {
            this.$u.toast(res.msg)
            // 更新购物车数量
            this.$store.dispatch('projectSetting/setGlobCartNumber')
          })
      })
    },
    // 开始学习
    onStartLearning() {
      let item = this.courseInfo
      // 直播
      if (item.course_type == 2) {
        // 是否有正在直播
        if (!this.$u.test.empty(item.section_live)) {
          this.onJumpLive(item)
        }
      } else {
        // 点播
        let sectionItem = item.recent_learn
        if (!this.$u.test.empty(sectionItem)) {
          // 缓存课时的item
          let sectionData = {
            id: sectionItem.section_id,
            course_id: sectionItem.course_id,
            section_rate: {
              current_time: sectionItem.current_time,
            },
            section_data: sectionItem.section_data,
            face_data: sectionItem.face_data,
          }
          this.directoryItemData = sectionData
          // 点播
          this.onJumpVideo(sectionItem)
        }
      }
    },
    // 进入点播播放
    onJumpVideo(item) {
      // 是否需要人脸识别
      if (this.courseInfo.onhook_type == 3) {
        this.$refs.refFaceVerify.onFaceMessage()
      } else {
        this.$store.commit('course/setCurrentPlayItem', this.directoryItemData)
        this.$u.route('/pageCourse/course/video/index', {
          id: this.courseInfo.id,
          sid: item.section_id,
        })
      }
    },
    // 进入直播
    onJumpLive(item) {
      let sectionId = item.section_live.room_no // 课时id
      let sectionData = {
        id: sectionId,
        course_id: item.section_live.course_id,
        section_live: item.section_live,
      }
      this.$store.commit('course/setCurrentPlayItem', sectionData)
      let viewertoken = item.section_live.authtype == 0 ? `${this.token.ak}:${this.token.sk}` : ''
      /* #ifdef H5 */
      if (item.section_live.live_type == 2) {
        // cc大班课
        this.$u.route('/pageCourse/cc_live/cc_live', {
          cc_room_id: item.section_live.cc_room_id,
          cc_userid: item.section_live.cc_userid,
          viewername: this.userInfo.nick_name,
          viewertoken: viewertoken,
        })
      } else if (item.section_live.live_type == 3) {
        // cc小班课
        this.$u.route('/pageCourse/cc_live/cc_small_class', {
          viewertoken: viewertoken,
          roomid: item.section_live.cc_room_id,
          userid: item.section_live.cc_userid,
        })
      }
      /* #endif */

      // #ifdef APP-PLUS
      // cc直播
      if (item.section_live.live_type === 2) {
        uni.showLoading({
          title: '登录中，请稍后',
        })
        setTimeout(() => {
          uni.hideLoading()
        }, 3000)
        // 云直播大班课
        ccLiveUniPlugin.loginLive(
          {
            roomId: item.section_live.cc_room_id,
            accountId: item.section_live.cc_userid,
            userName: this.userInfo.nick_name,
            password: viewertoken,
          },
          (ret) => {
            let data = JSON.parse(ret)
            this.$u.toast(data.msg)
          }
        )
      } else if (item.section_live.live_type === 3) {
        // 云课堂小班课
        // role	登录角色，取值说明："0"为讲师，"1"为学员，"2"为旁听，"3"为隐身者，"4"为助教
        uni.showLoading({
          title: '登录中，请稍后',
        })
        setTimeout(() => {
          uni.hideLoading()
        }, 3000)
        ccSsktUniPlugin.loginByAccount(
          {
            roomId: item.section_live.cc_room_id,
            accountId: item.section_live.cc_userid,
            role: 1,
            userName: this.userInfo.nick_name,
            password: viewertoken,
          },
          (ret) => {
            let data = JSON.parse(ret)
            this.$u.toast(data.msg)
          }
        )
      }
      // #endif
    },
    // 加入课程
    onJion(price, pro_id) {
      if (pro_id == undefined) {
        var pro_id = 0
      } else {
        if (this.courseInfo.hasOwnProperty('bargain_done')) {
          if (this.courseInfo.bargain_done == 1) {
            var pro_id = pro_id
          } else {
            var pro_id = 0
          }
        } else {
          var pro_id = pro_id
        }
      }
      this.$edu.judgeLogin(() => {
        if (price == 0) {
          this.$edu.api
            .createCourseStudentJoin({
              course_id: this.options.id,
            })
            .then((res) => {
              this.$emit('click')
            })
        } else if (price > 0) {
          this.$u.route('/pageCourse/cart/course', {
            id: this.options.id,
            promotion_id: pro_id,
          })
        }
      })
    },
    // 资讯
    pathMessage(url) {
      // #ifdef APP-PLUS
      if (/^[0-9]+$/.test(url)) {
        plus.runtime.openURL(`https://wpa.qq.com/msgrd?v=3&uin=${url}&site=qq&menu=yes`)
      } else {
        plus.runtime.openURL(url)
      }
      // #endif

      // #ifdef H5
      if (/^[0-9]+$/.test(url)) {
        window.location.href = 'https://wpa.qq.com/msgrd?v=3&uin=' + url + '&site=qq&menu=yes'
      } else {
        window.location.href = url
      }
      // #endif

      // #ifdef MP-WEIXIN
      if (this.globConfigInit.site_info.tel) {
        uni.makePhoneCall({
          phoneNumber: this.globConfigInit.site_info.tel,
        })
      }
      // #endif
    },
    // 发起拼团
    handleAddPintuan() {
      this.showPintuan = true
    },
    // 跳转
    onJump(url, params) {
      this.$u.route(url, params)
    },
    handleAddPintuan_nopay(status) {
      if (status == 0) {
        this.$u.toast('已入团成功，请确认支付')
      }
    },
    // 人脸验证
    onFaceVerifyConfirm(file) {
      uploadFile('/user/tencent/face/person/verify', file, {
        scene_key: 'course_section',
        scene_id: this.directoryItemData.id,
        scene_type: 1,
      })
        .then((res) => {
          this.$store.commit('course/setCurrentPlayItem', this.directoryItemData)
          this.$u.toast(res.msg)
          this.$refs.refFaceVerify.onClose()
          this.$u.route('/pageCourse/course/video/index', {
            id: this.directoryItemData.course_id,
            sid: this.directoryItemData.id,
          })
        })
        .catch((err) => {
          this.$u.toast(err.msg)
          this.$refs.refFaceVerify.resetPhoto()
        })
    },
  },
}
</script>

<style lang="scss" scoped>
.submit-bar .placeholder {
  height: 108rpx;
}
.navigation {
  display: flex;
  border: solid 2rpx #f2f2f2;
  background-color: #ffffff;
  padding: 16rpx 30rpx;
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  z-index: 998;
  .left {
    display: flex;
    font-size: 20rpx;
    .item {
      margin-right: 40rpx;
      text-align: center;
      .text {
        font-size: 22rpx;
        font-weight: 400;
        color: #909399;
      }
    }
  }
  .right {
    display: flex;
    align-items: center;
    flex: 1;
    .btn {
      flex: 1;
      height: 72rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 39rpx;
      font-size: 32rpx;
      font-weight: 400;
    }
    .cart {
      margin-right: 16rpx;
      border-width: 2rpx;
      border-style: solid;
      @include text-color();
      @include border-color();
    }
    .buy {
      color: #ffffff;
      @include bg-color();
    }
    .big {
      width: 496rpx;
      color: #ffffff;
      @include bg-color();
    }
  }
}
</style>
